#!/usr/bin/env bash

TAR_NAME=
BUILD_PATH=/root/rpmbuild
BASEDIR=$(cd `dirname $0`; pwd)
ACTION=$1

function build_env() {
    mkdir -p ${BUILD_PATH}
    cd ${BUILD_PATH}
    rm -rf ${BUILD_PATH}/{BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
    mkdir {BUILD,BUILDROOT,RPMS,SOURCES,SPECS,SRPMS}
}

function build_source_code_pkg() {
    cd ${BASEDIR}
    TAR_NAME=$(rpmspec -P ancert.spec|egrep "Name|Version"|awk '{print $NF}'|xargs|tr " " "-"|awk '{sub("-","-v");print}')
    rm -rf ${BUILD_PATH}/tmp/${TAR_NAME}
    mkdir -p ${BUILD_PATH}/tmp/${TAR_NAME}
    for i in $(ls |egrep -v "*.sh");do
        cp -arf $i ${BUILD_PATH}/tmp/${TAR_NAME}/
    done
    cd ${BUILD_PATH}/tmp/
    tar -czf ${TAR_NAME}.tar.gz ${TAR_NAME}
    echo "source code: ${BUILD_PATH}/tmp/${TAR_NAME}.tar.gz"
}

function build_rpm() {
    build_env
    build_source_code_pkg || { echo "Error: Failed to build the source package";exit 1; }
    cd ${BUILD_PATH}/tmp
    rpmbuild -tb ${TAR_NAME}.tar.gz
}

function usage() {
    echo "Usage: ./$0 [spec|rpm]"
    exit 1
}

#########################main##############################
if [ $# -ne 1 ] || ! echo "$ACTION" | egrep -q "spec|rpm"; then
    usage
fi

if [ "$ACTION" == "spec" ]; then
    build_env
    build_source_code_pkg || { echo "Error: Failed to build the source package";exit 1; }
elif [ "$ACTION" == "rpm" ]; then
    build_rpm
fi
